﻿using Common;
using Microsoft.Win32;
using NewDevice;
using NewDevice.RS485;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfCommCtl.Controls;

namespace WpfCommCtlTest
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainWindowViewModel();
        }

        public MainWindow(string licenseCheckedMsg)
        {
            InitializeComponent();
            this.DataContext = new MainWindowViewModel();
            //var tmp = licenseCheckedMsg.Split(',');
            //tbLicenseChecked.Text = $"到期日期{tmp[0]} 剩余{tmp[1]}天";
            tbLicenseChecked.Text = licenseCheckedMsg;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.ImportGerberView.Visibility = Visibility.Visible;
        }

        private void btnGenerateLicense_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                /// test mylog class
                {
                    Mylog.Info(
                        message: $"液位={23}",
                        deviceName: "abc"

                    );
                    Mylog.DeviceData(sendData: "FF FF FF", deviceName: "DM3058E");

                    try
                    {
                        throw new Exception("hahaha");
                    }
                    catch (Exception ex)
                    {
                        Mylog.Error(ex);
                    }
                }

                var dt = dpGenerateLicense.Text;
                var datetime = DateTime.ParseExact(dt, "yyyy/M/d", null);
                //License.Key = tbKey.Text;
                License.GenrateLiceseFile(datetime);
                tbEncryptedString.Text = License.EncryptedString;
                Thread.Sleep(1001);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btCopy_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Clipboard.SetText(tbEncryptedString.Text);
            }
            catch (COMException ex)
            {
                if (ex.HResult == unchecked((int)0x800401D0))
                {
                    MessageBox.Show("无法访问剪贴板。可能被其他应用程序占用或系统权限不足。");
                }
                else
                {
                    throw; // 重新抛出其他类型的异常
                }
            }
        }

        private void btnCheckLicense_Click(object sender, RoutedEventArgs e)
        {
            string msg;
            License.Check(out msg);
            tbLicenseChecked.Text = msg;
        }

        private void btSelectSn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 创建文件选择对话框
                OpenFileDialog openFileDialog = new OpenFileDialog();

                // 设置对话框的标题和默认文件名（可选）
                openFileDialog.Title = "选择一个sn文件";
                openFileDialog.FileName = "";

                // 设置文件过滤器，限制用户只能选择特定类型的文件
                openFileDialog.Filter = "文本文件 (*.sn)|*.sn|所有文件 (*.*)|*.*";

                // 如果需要，可以设置默认文件夹
                openFileDialog.InitialDirectory = Environment.CurrentDirectory;

                // 打开文件选择对话框并等待用户选择文件
                if (openFileDialog.ShowDialog() == true)
                {
                    // 用户选择了文件
                    string selectedFilePath = openFileDialog.FileName;

                    // 在这里可以处理所选文件的路径（例如，打开和读取文件）
                    this.tbKey.Text = License.GetSN(selectedFilePath);
                }
                else
                {
                    // 用户取消了选择
                    Console.WriteLine("用户取消了文件选择。");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private SerialBase com;
        private LC10P LC10P;

        /// <summary>
        /// connect
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                com = new SerialBase("test");
                com.Connect(port.Text, 57200);
            }
            catch (Exception ex)
            {
                recvCmd.Text = ex.Message;
            }
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            try
            {
                com.Close();
            }
            catch (Exception ex)
            {
                recvCmd.Text = ex.Message;
            }
        }

        private static byte[] HexStringToBytes(string hexString)
        {
            // 移除字符串中的空格
            hexString = hexString.Replace(" ", "");

            // 每两个字符转为一个字节
            return Enumerable.Range(0, hexString.Length / 2)
                             .Select(i => Convert.ToByte(hexString.Substring(i * 2, 2), 16))
                             .ToArray();
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            try
            {
                //var recv = com.SendBytesAndWaitResponse(HexStringToBytes(sendCmd.Text), 6);
                //recvCmd.Text = BitConverter.ToString(recv);
            }
            catch (Exception ex)
            {
                recvCmd.Text = ex.Message;
            }
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            try
            {
                LC10P = new LC10P(com);
                LC10P.Speed = 100;
                LC10P.MotorMode = MotorModes.speedMode;
                LC10P.Init(10);
                LC10P.MotorSpeed(10, 0);
            }
            catch (Exception ex)
            {
                recvCmd.Text = ex.Message;
            }
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            try
            {
                LC10P.MotorSpeed(10, Convert.ToInt16(tbMotorSpeed.Text));
            }
            catch (Exception ex)
            {
                recvCmd.Text = ex.Message;
            }
        }

        private void Button_Click_6(object sender, RoutedEventArgs e)
        {
            try
            {
                LC10P.MotorSpeed(10, 0);
            }
            catch (Exception ex)
            {
                recvCmd.Text = ex.Message;
            }
        }

        private void Button_Click_8(object sender, RoutedEventArgs e)
        {
            pQW_IO.DOCount = 4;
            //Task.Run(() => {
            while (true)
            {
                pQW_IO.GetDO(1);
                var sts = pQW_IO.GetDO(int.Parse(tbPQW_IO_chl.Text));
                Thread.Sleep(100);
            }
        }

        private void Button_Click_9(object sender, RoutedEventArgs e)
        {
            pQW_IO.DICount = 4;
            //Task.Run(() => {
            while (true)
            {
                pQW_IO.GetDI(1);
                var sts = pQW_IO.GetDI(int.Parse(tbPQW_IO_chl.Text));
                Thread.Sleep(100);
            }
            //});
            //tbPqw_io_message.Text = $"di sts = [{sts}]";
        }

        private PQW_IO pQW_IO = null;

        private void Button_Click_10(object sender, RoutedEventArgs e)
        {
            com = new SerialBase("test");
            com.Connect(tbPQW_IO_port.Text, 9600);
            pQW_IO = new PQW_IO(com, 1);
        }

        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            pQW_IO.SetDO(int.Parse(tbPQW_IO_chl.Text), tbPQW_IO_sts.Text == "1");
        }

        private void Button_Click_11(object sender, RoutedEventArgs e)
        {
            Task.Run(() =>
            {
                try
                {
                    isRead = true;
                    while (isRead)
                    {
                        pqw16.ReadDiStatus();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            });
        }

        private void Button_Click_12(object sender, RoutedEventArgs e)
        {
            Task.Run(() =>
            {
                try
                {
                    isWrite = true;
                    bool sts = false;
                    while (isWrite)
                    {
                        pqw16.WriteDo(3, sts);
                        sts = !sts;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            });
        }

        private void Button_Click_13(object sender, RoutedEventArgs e)
        {
            isRead = false;
        }

        private void Button_Click_14(object sender, RoutedEventArgs e)
        {
            isWrite = false;
        }

        private SerialBase_V2 serial = new SerialBase_V2("COM13", 9600);
        private PQW_IO_V2 pqw16;
        private bool isRead;
        private bool isWrite;

        private void Button_Click_15(object sender, RoutedEventArgs e)

        {
            SerialBase_V2.Activate();
            serial.OpenPort();

            pqw16 = new PQW_IO_V2(1, serial, 16, 16);
        }

        private bool isExternRead = false;

        private void Button_Click_16(object sender, RoutedEventArgs e)
        {
            Task.Run(() =>
            {
                try
                {
                    isExternRead = true;

                    while (isExternRead)
                    {
                        for (global::System.Int32 i = 0; i < 16; i++)
                        {
                            pqw16.GetDi(i);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            });

            Task.Run(() =>
            {
                try
                {
                    isExternRead = true;

                    while (isExternRead)
                    {
                        for (global::System.Int32 i = 0; i < 16; i++)
                        {
                            pqw16.GetDo(i);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            });
        }

        private void Button_Click_17(object sender, RoutedEventArgs e)
        {
            isExternRead = false;
        }

        private void tbKey_PreviewDrop(object sender, DragEventArgs e)
        {
            try
            {
                // 恢复文本框样式
                tbKey.BorderBrush = System.Windows.Media.Brushes.Gray;

                // 检查是否包含文件数据
                if (!e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    MessageBox.Show("错误: 拖放的内容不是文件");
                    return;
                }

                // 获取拖放的文件路径数组
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

                if (files == null || files.Length == 0)
                {
                    MessageBox.Show("错误: 没有找到文件");
                    return;
                }

                // 处理文件路径

                this.tbKey.Text = License.GetSN(files[0]);
                // 标记事件已处理
                e.Handled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"处理文件时出错: {ex.Message}");
            }
        }

        private void tbKey_PreviewDragOver(object sender, DragEventArgs e)
        {
            try
            {
                // 检查拖放的数据是否包含文件
                bool isFileAvailable = e.Data.GetDataPresent(DataFormats.FileDrop);

                if (isFileAvailable)
                {
                    // 设置拖放效果为复制
                    e.Effects = DragDropEffects.Copy;

                    // 改变文本框边框颜色提供视觉反馈
                    tbKey.BorderBrush = System.Windows.Media.Brushes.Green;
                    tbKey.BorderThickness = new Thickness(2);
                }
                else
                {
                    e.Effects = DragDropEffects.None;
                    tbKey.BorderBrush = System.Windows.Media.Brushes.Red;
                }

                e.Handled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"拖放错误: {ex.Message}");
            }
        }
    }
}